﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
using ByteSite.DBUtility;
using ByteSite.Common;
using SqlSugar;

namespace ByteSite.DAL
{
    /// <summary>
    /// 数据访问类:文章类别表
    /// </summary>
    public partial class article_category
    {
        private string databaseprefix;//数据库表名前缀
        public SqlSugarClient db;
        public article_category(string _databaseprefix)
        {
            databaseprefix = _databaseprefix;
            db = new DBUtility.DbContext().Db;
        }

        #region 基本方法================================

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Entitys.dt_article_category model)
        {
            try
            {
                db.BeginTran();
                model.id = db.Insertable<Entitys.dt_article_category>(model).ExecuteReturnIdentity();
                //查询父节点的深度赋值
                if (model.parent_id > 0)
                {
                    Entitys.dt_article_category model2 = db.Queryable<Entitys.dt_article_category>().Where(x => x.id == model.parent_id).First();
                    model.class_list = model2.class_list + model.id + ",";
                    model.class_layer = model2.class_layer + 1;
                }
                else
                {
                    model.class_list = "," + model.id + ",";
                    model.class_layer = 1;
                }
                db.Updateable<Entitys.dt_article_category>().SetColumns(x => new Entitys.dt_article_category() { class_list = model.class_list, class_layer = model.class_layer }).Where(x => x.id == model.id).ExecuteCommand();

                #region 栏目规格===========================
                if (model.category_specs != null)
                {
                    foreach (Entitys.dt_article_category_spec modelt in model.category_specs)
                    {
                        db.Insertable<Entitys.dt_article_category_spec>(new Entitys.dt_article_category_spec() { category_id = model.id, spec_id = modelt.spec_id }).ExecuteCommand();
                    }
                }
                #endregion

                db.CommitTran();
            }
            catch
            {
                db.RollbackTran();
            }
            return model.id;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Entitys.dt_article_category model)
        {
            try
            {
                db.BeginTran();
                if (IsContainNode(model.id, Utils.ObjToInt(model.parent_id)))
                {
                    Entitys.dt_article_category oldModel = db.Queryable<Entitys.dt_article_category>().Where(x => x.id == model.id).First();
                    //查找旧父节点数据
                    string class_list = "," + model.parent_id + ",";
                    int class_layer = 1;
                    if (oldModel.parent_id > 0)
                    {
                        Entitys.dt_article_category oldParentModel = db.Queryable<Entitys.dt_article_category>().Where(x => x.id == oldModel.parent_id).First();
                        class_list = oldParentModel.class_list + model.parent_id + ",";
                        class_layer = Utils.ObjToInt(oldParentModel.class_layer + 1);
                    }
                    //先提升选中的父节点
                    db.Updateable<Entitys.dt_article_category>().SetColumns(x => new Entitys.dt_article_category() { parent_id = oldModel.parent_id, class_list = class_list, class_layer = class_layer }).Where(x => x.id == model.parent_id).ExecuteCommand();
                    UpdateChilds(Utils.ObjToInt(model.parent_id));//带事务
                }
                //更新子节点
                if (model.parent_id > 0)
                {
                    Entitys.dt_article_category model2 = db.Queryable<Entitys.dt_article_category>().Where(x => x.id == model.parent_id).First();
                    model.class_list = model2.class_list + model.id + ",";
                    model.class_layer = model2.class_layer + 1;
                }
                else
                {
                    model.class_list = "," + model.id + ",";
                    model.class_layer = 1;
                }
                //更新本栏目类别信息
                db.Updateable<Entitys.dt_article_category>(model).ExecuteCommand();
                //更新子节点
                UpdateChilds(model.id);
                #region 栏目规格===========================
                //删除已删除的栏目规格
                db.Deleteable<Entitys.dt_article_category_spec>().Where(x => x.category_id == model.id);
                //添加/修改栏目规格
                if (model.category_specs != null)
                {
                    foreach (Entitys.dt_article_category_spec modelt in model.category_specs)
                    {
                        if (modelt.id > 0)
                        {
                            db.Updateable<Entitys.dt_article_category_spec>().SetColumns(x => new Entitys.dt_article_category_spec() { category_id = modelt.category_id, spec_id = modelt.spec_id }).Where(x => x.id == model.id).ExecuteCommand();
                        }
                        else
                        {
                            db.Insertable<Entitys.dt_article_category_spec>(new Entitys.dt_article_category_spec() { category_id = model.id, spec_id = modelt.spec_id }).ExecuteCommand();
                        }
                    }
                }
                #endregion

                db.CommitTran();
            }
            catch(Exception ex)
            {
                db.RollbackTran();
            }
            return true;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int id)
        {
            try
            {
                db.BeginTran();
                db.Deleteable<Entitys.dt_article_category_spec>().Where(x => x.category_id == id).ExecuteCommand();
                db.Deleteable<Entitys.dt_article_category>().Where(x => x.class_list.Contains(id.ToString())).ExecuteCommand();
                db.CommitTran();
            }
            catch
            {
                db.RollbackTran();
                return false;
            }
            return true;
        }

        /// <summary>
        /// 取得所有类别列表
        /// </summary>
        /// <param name="parent_id">父ID</param>
        /// <param name="channel_id">频道ID</param>
        /// <returns></returns>
        public List<Entitys.dt_article_category> GetList(int parent_id, int channel_id)
        {
            List<Entitys.dt_article_category> oldList = db.Queryable<Entitys.dt_article_category>().Where(x => x.channel_id == channel_id).OrderBy(x => x.sort_id, OrderByType.Asc).OrderBy(x => x.id, OrderByType.Desc).ToList();
            if (oldList == null)
                return null;
            //List<Entitys.dt_article_category> newList = Utils.ClassClone<List<Entitys.dt_article_category>>(oldList);
            List<Entitys.dt_article_category> newList = new List<Entitys.dt_article_category>();
            GetChilds(oldList, newList, parent_id, channel_id);
            return newList;
        }
        #endregion


        #region 私有方法================================
        /// <summary>
        /// 从内存中取得所有下级类别列表（自身迭代）
        /// </summary>
        private void GetChilds(List<Entitys.dt_article_category> oldData, List<Entitys.dt_article_category> newData, int parent_id, int channel_id)
        {
            List<Entitys.dt_article_category> list = oldData.FindAll(x => x.parent_id == parent_id);
            foreach (Entitys.dt_article_category model in list)
            {
                newData.Add(model);

                this.GetChilds(oldData, newData, model.id, channel_id);
            }
        }

        /// <summary>
        /// 修改子节点的ID列表及深度（自身迭代）
        /// </summary>
        private void UpdateChilds(int parent_id)
        {
            //查找父节点信息
            Entitys.dt_article_category model = db.Queryable<Entitys.dt_article_category>().Where(x => x.id == parent_id).First();
            if (model != null)
            {
                //查找子节点
                List<Entitys.dt_article_category> list = db.Queryable<Entitys.dt_article_category>().Where(x => x.parent_id == parent_id).ToList();
                if (list.Count > 0)
                {
                    foreach (Entitys.dt_article_category modelt in list)
                    {
                        //修改子节点的ID列表及深度
                        int id = modelt.id;
                        string class_list = model.class_list + id + ",";
                        int class_layer = Utils.ObjToInt(model.class_layer) + 1;
                        db.Updateable<Entitys.dt_article_category>().SetColumns(x => new Entitys.dt_article_category() { class_list = class_list, class_layer = class_layer }).Where(x => x.id == id).ExecuteCommand();
                        this.UpdateChilds(id);
                    }
                }
             }
        }

        /// <summary>
        /// 验证节点是否被包含
        /// </summary>
        /// <param name="id">待查询的节点</param>
        /// <param name="parent_id">父节点</param>
        /// <returns>bool</returns>
        private bool IsContainNode(int id, int parent_id)
        {
            return db.Queryable<Entitys.dt_article_category>().Count(x => x.class_list.Contains(id.ToString()) && x.id == parent_id) > 0;
        }

        #endregion
    }
}